package com.diamond.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.diamond.action.Page;
import com.diamond.bo.ClientOrderBO;
import com.diamond.bo.ClientOrderDetailBO;
import com.diamond.bo.FormulaBO;
import com.diamond.bo.OrderBO;
import com.diamond.bo.QueryOrderBO;
import com.diamond.bo.ReturnBO;
import com.diamond.entity.Clientorder;
import com.diamond.entity.Clientorderdetail;
import com.diamond.entity.Diamond;
import com.diamond.entity.Formula;
import com.diamond.entity.Supporderdetail;
import com.diamond.facade.ClientorderFacade;
import com.diamond.facade.CommonFacade;
import com.diamond.po.ClientOrderPO;
import com.diamond.service.IClientorderService;
import com.diamond.util.DateUtils;
import com.diamond.util.DiamondUtil;
import com.diamond.util.StringUtil;

/**
 * @author JSmart Tools
 */
@SuppressWarnings("unchecked")
public class ClientorderService extends Service<ClientOrderPO> implements IClientorderService {

	public ReturnBO<ClientOrderBO> queryClientOrder(QueryOrderBO queryOrderBo)
			throws Exception {
		ReturnBO<ClientOrderBO> returnBo = new ReturnBO<ClientOrderBO>();
		StringBuilder querySql = new StringBuilder("select distinct * from clientorder c, user u  where c.user_id=u.user_id and c.del_state = 0");
		StringBuilder totalSql = new StringBuilder("select distinct * from clientorder c, user u  where c.user_id=u.user_id and c.del_state = 0");
		if (!"".equals(queryOrderBo.getClientName()) && null != queryOrderBo.getClientName()) {
			querySql.append(" and u.user_name like '%").append(queryOrderBo.getClientName()).append("%'");
			totalSql.append(" and u.user_name like '%").append(queryOrderBo.getClientName()).append("%'");
		}
		if (!"".equals(queryOrderBo.getOrderDateFrom()) && null != queryOrderBo.getOrderDateFrom()
				&& !"".equals(queryOrderBo.getOrderDateTo()) && null != queryOrderBo.getOrderDateTo()) {
			querySql.append(" and (c.order_date BETWEEN '").append(queryOrderBo.getOrderDateFrom()).append("' and '").append(queryOrderBo.getOrderDateTo()).append("')");
			totalSql.append(" and (c.order_date BETWEEN '").append(queryOrderBo.getOrderDateFrom()).append("' and '").append(queryOrderBo.getOrderDateTo()).append("')");
		} 
		if (!"".equals(queryOrderBo.getOrderNo()) && null != queryOrderBo.getOrderNo()) {
			querySql.append(" and c.order_no like '").append(queryOrderBo.getOrderNo()).append("%'");
			totalSql.append(" and c.order_no like '").append(queryOrderBo.getOrderNo()).append("%'");
		}
		querySql.append(" order by c.order_date desc").append(" limit ").append(queryOrderBo.getStart()).append(", ").append(queryOrderBo.getPageSize());
		
		List<ClientOrderBO> list = super.genericDAO.findBySqlToObj(querySql.toString(), ClientOrderBO.class);
		for (ClientOrderBO clientOrderBo : list) {
			clientOrderBo.setMidTotal(StringUtil.doubleFmt(clientOrderBo.getMidTotal()));
			clientOrderBo.setTotal(StringUtil.doubleFmt(clientOrderBo.getTotal()));
		}
		List totallist = super.genericDAO.findBySqlToObj(totalSql.toString(), null);
		returnBo.setPageSize(queryOrderBo.getPageSize());
		returnBo.setStart(queryOrderBo.getStart());
		returnBo.setReturnBolist(list);
		returnBo.setType(2);
		returnBo.setTotalSize(totallist.size());
		return returnBo;
	}

	public OrderBO queryClientOrderById(String cliOrdMasterId) throws Exception {
		OrderBO orderBo = new OrderBO();
		String queryMasterSql = "select * from clientorder c, user u where c.user_id=u.user_id and c.del_state = 0 and c.cliOrdMaster_id='" + cliOrdMasterId + "'";
		String queryDetailSql = "select * from clientorderdetail d where d.cliOrdMaster_id='" + cliOrdMasterId + "'";
		List<ClientOrderBO> cordlist = super.genericDAO.findBySqlToObj(queryMasterSql, ClientOrderBO.class);
		List<ClientOrderDetailBO> corddlist = super.genericDAO.findBySqlToObj(queryDetailSql, ClientOrderDetailBO.class);
		if (cordlist.size() > 0 && cordlist.size()==1 && corddlist.size() > 0) {
			ClientOrderBO clientOrderBo = cordlist.get(0);
			String queryAgentFormulaSql = "select * from formula where user_id in (select parent_agent_id from user where user_id="+clientOrderBo.getUserId()+")";
			List<FormulaBO> formulalist = super.genericDAO.findBySqlToObj(queryAgentFormulaSql, FormulaBO.class);
			if (formulalist.size() > 0 && formulalist.size() == 1) {
				FormulaBO formulaBo = formulalist.get(0);
				clientOrderBo.setCostTotal(StringUtil.doubleFmt(clientOrderBo.getMidTotal()/formulaBo.getRate()));
			} else {
				clientOrderBo.setCostTotal(StringUtil.doubleFmt(clientOrderBo.getMidTotal()));
			}
			clientOrderBo.setMidTotal(StringUtil.doubleFmt(clientOrderBo.getMidTotal()));
			clientOrderBo.setTotal(StringUtil.doubleFmt(clientOrderBo.getTotal()));
			orderBo.setClientOrderBo(clientOrderBo);
			orderBo.setClientOrderDetaillist(corddlist);
		}
		return orderBo;
	}

	@Override
	public void save(Clientorder clientOrder, Collection<Clientorderdetail> coll,Object angent_id)
			throws Exception {
		Clientorder order=(Clientorder) genericDAO.merge(clientOrder);
		if(coll!=null&&coll.size()>0){
			Double midTotal=0d;
			for(Clientorderdetail detail:coll){
				List list=genericDAO.findByHQL("from Diamond where batch='"+detail.getBatch()+"'");
				if(list==null||list.size()==0)continue;
				Diamond diamond = (Diamond) list.get(0);
				
				List<Formula> supFormulas = genericDAO.findByHQL("from Formula where state=1 order by importance");
				
				List<Formula> angentFormulas =new ArrayList<Formula>();
				if(angent_id!=null){
					List<Formula> fms = genericDAO.findByHQL("from Formula where userId="+angent_id+" order by importance");
					if(fms!=null&&fms.size()>0)angentFormulas=fms;
				}
				for (Formula formula : supFormulas){
					if(DiamondUtil.suitFormula(formula, diamond)){
						Double price=diamond.getSupPrice()*formula.getRate();
			
						for (Formula angentFormula : angentFormulas){
							if(DiamondUtil.suitFormula(angentFormula, diamond)){
								price=price*angentFormula.getRate();
							}
						}
						detail.setMidPrice(price);
						midTotal+=price;
						break;
					}
					
					
				}
				detail.setCliOrdMasterId(order.getCliOrdMasterId());
				detail.setOrderDate(order.getOrderNo());
				detail.setOrderDate(DateUtils.getStringDateShort());
				detail.setPayState("0");
				genericDAO.save(detail);
				
				Supporderdetail supDetail = new Supporderdetail();
	    		supDetail.setAmount(1);
	    		supDetail.setBatch(detail.getBatch());
	    		supDetail.setClarity(detail.getClarity());
	    		supDetail.setColor(detail.getColor());
	    		supDetail.setFinalCut(detail.getFinalCut());
	    		supDetail.setFluor(detail.getFluor());
	    		supDetail.setHR(detail.getHR());
	    		supDetail.setLab(detail.getLab());
	    		supDetail.setName("钻石");
	    		supDetail.setPolish(detail.getPolish());
	    		supDetail.setReportNo(detail.getReportNo());
	    		supDetail.setShape(detail.getShape());
	    		supDetail.setState("0");
	    		supDetail.setSupplierName(detail.getSupplierName());
	    		supDetail.setSymmetry(detail.getSymmetry());
	    		supDetail.setWeight(detail.getWeight());
	    		supDetail.setOrderDate(DateUtils.getStringDateShort());
	    		if(list!=null&&list.size()>0)supDetail.setPrice(diamond.getSupPrice());
	    		genericDAO.save(supDetail);
	    		
	    		String HQL="delete from Diamond where batch='"+detail.getBatch()+"' and supplierName='"+detail.getSupplierName()+"'";
	    		genericDAO.bulkUpdate(HQL);
			}
			order.setMidTotal(midTotal);
    		genericDAO.update(order);
		}
		
	}

	public Clientorder findByNO(String orderNO) {
		List list=genericDAO.findByHQL("from Clientorder where orderNo='"+orderNO+"'");
		if(list!=null&&list.size()>0)return (Clientorder) list.get(0);
		return null;
	}

	@Override
	public List findOrderList(Long userId, ClientOrderBO clientOrderBo,ClientorderFacade clientOrderFacade,Integer pageSize)
			throws Exception {
		StringBuilder HQL = new StringBuilder("from Clientorder where userId=").append(userId).append(" and delState ='0'"); 
		
		if (!StringUtil.isEmpty(clientOrderBo.getOrderNo())) {
			HQL.append(" and orderNo like '%").append(clientOrderBo.getOrderNo()).append("%' ");
		}
		if (!StringUtil.isEmpty(clientOrderBo.getBuyerName())) {
			HQL.append(" and buyerName like '%").append(clientOrderBo.getBuyerName()).append("%' ");
		}
		if (!"-1".equals(clientOrderBo.getOrderStatus())) {
			HQL.append(" and orderStatus='").append(clientOrderBo.getOrderStatus()).append("' ");
		}
		if (!StringUtil.isEmpty(clientOrderBo.getOrderDateFr()) && !StringUtil.isEmpty(clientOrderBo.getOrderDateTo())) {
			HQL.append(" and (orderDate between '").append(clientOrderBo.getOrderDateFr()).append("' and '").append(clientOrderBo.getOrderDateTo()).append("') ");
		}
		if (!StringUtil.isEmpty(clientOrderBo.getOrderPriceFr()) && !StringUtil.isEmpty(clientOrderBo.getOrderPriceTo())) {
			HQL.append(" and (total >= ").append(clientOrderBo.getOrderPriceFr()).append(" and total <= ").append(clientOrderBo.getOrderPriceTo()).append(") ");
		}
		
		HQL.append(" order by orderDate desc");
		String url = "findOrderList.action?a=1";
		List list = Page.util(ServletActionContext.getRequest(),url,clientOrderFacade,HQL.toString(),pageSize);
		return list;
	}

	@Override
	public List findCentOrderList(Long userId, ClientOrderBO clientOrderBo,ClientorderFacade clientOrderFacade, Integer pageSize) throws Exception {
		StringBuilder HQL = new StringBuilder("from Clientorder where userId=").append(userId).append(" and delState ='0'"); 
		
		if (!StringUtil.isEmpty(clientOrderBo.getOrderNo())) {
			HQL.append(" and orderNo like '%").append(clientOrderBo.getOrderNo()).append("%' ");
		}
		if (!StringUtil.isEmpty(clientOrderBo.getBuyerName())) {
			HQL.append(" and buyerName like '%").append(clientOrderBo.getBuyerName()).append("%' ");
		}
		if (!"-1".equals(clientOrderBo.getOrderStatus())) {
			HQL.append(" and orderStatus='").append(clientOrderBo.getOrderStatus()).append("' ");
		}
		if (!StringUtil.isEmpty(clientOrderBo.getOrderDateFr()) && !StringUtil.isEmpty(clientOrderBo.getOrderDateTo())) {
			HQL.append(" and (orderDate between '").append(clientOrderBo.getOrderDateFr()).append("' and '").append(clientOrderBo.getOrderDateTo()).append("') ");
		}
		if (!StringUtil.isEmpty(clientOrderBo.getOrderPriceFr()) && !StringUtil.isEmpty(clientOrderBo.getOrderPriceTo())) {
			HQL.append(" and (midTotal >= ").append(clientOrderBo.getOrderPriceFr()).append(" and midTotal <= ").append(clientOrderBo.getOrderPriceTo()).append(") ");
		}
		
		HQL.append(" order by orderDate desc");
		String url = "findCentOrderList.action?a=1";
		List list = Page.util(ServletActionContext.getRequest(),url,clientOrderFacade,HQL.toString(),pageSize);
		return list;
	}
 

}
